<template>
    <el-dialog :title="titleMap[mode]" v-model="visible" :width="500" destroy-on-close @closed="$emit('closed')">
        <el-form :model="form" :rules="rules" :disabled="mode=='show'" ref="dialogFormRef" label-width="100px" label-position="left">
			<!-- <el-form-item :label="$t('user.table.avatar')" prop="avatar">
				<sc-upload v-model="form.avatar" :title="$t('user.table.uploadAvatar')"></sc-upload>
			</el-form-item> -->
			<el-form-item :label="$t('user.table.username')" prop="username">
				<el-input v-model="form.username" :disabled="form.id == '1'" :placeholder="$t('user.usernameRulePlaceholder')" clearable></el-input>
			</el-form-item>
			<el-form-item :label="$t('user.table.name')" prop="name">
				<el-input v-model="form.name" :placeholder="$t('user.nameRulePlaceholder')" clearable></el-input>
			</el-form-item>
			<template v-if="mode=='add'">
				<el-form-item :label="$t('user.table.loginPassword')" prop="password">
					<el-input type="password" v-model="form.password" :placeholder="$t('user.passwordRulePlaceholder')" clearable show-password></el-input>
				</el-form-item>
				<el-form-item :label="$t('user.table.confirmPassword')" prop="password2">
					<el-input type="password" v-model="form.password2" :placeholder="$t('user.password2RulePlaceholder')" clearable show-password></el-input>
				</el-form-item>
			</template>
			<el-form-item :label="$t('user.table.email')">
				<el-input v-model="form.email" :placeholder="$t('user.table.emailPlaceholder')" clearable></el-input>
			</el-form-item>
			<el-form-item :label="$t('user.table.phone')">
				<el-input v-model="form.phone" :placeholder="$t('user.table.phonePlaceholder')" clearable></el-input>
			</el-form-item>
			<el-form-item :label="$t('user.table.position')">
				<el-input v-model="form.position" :placeholder="$t('user.table.positionPlaceholder')" clearable></el-input>
			</el-form-item>
			<el-form-item :label="$t('user.table.dept')" prop="dept_id">
				<el-cascader v-model="form.dept_id" ref="deptRef" :options="depts" :props="deptsProps" clearable style="width: 100%;"></el-cascader>
			</el-form-item>
			<el-form-item :label="$t('user.table.rule')" prop="role_list">
				<el-select v-model="form.role_list" multiple filterable style="width: 100%">
					<el-option v-for="item in groups" :key="item.id" :label="item.name" :value="item.id"/>
				</el-select>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible=false">{{ $t('common.cancel') }}</el-button>
			<el-button type="primary" :loading="isSaveing" @click="submit">{{ $t('common.save') }}</el-button>
		</template>
    </el-dialog>
</template>
<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import api from '@/api';
import i18n from '@/locales';
import { ElMessage } from "element-plus";

// 定义用于发射方法
const emit = defineEmits(['success', 'closed']);
// 定义响应式数据
const mode = ref('add');
const dialogFormRef = ref(null);
const titleMap = reactive({
    add:  i18n.global.t('common.add') + i18n.global.t('user.user'),
    edit: i18n.global.t('common.edit') + i18n.global.t('user.user'),
});
const visible = ref(false);
const isSaveing = ref(false);
const deptRef = ref(null);
const form = reactive({
    id: "",
    username: "",
    avatar: "",
    name: "",
    email: "",
    phone: "",
    status: 1,
    position: "",
    dept_id: "",
    role_list: [],
});
const rules = computed(() => ({
    avatar: [{ required: true, message: i18n.global.t('user.avatarRulePlaceholder') }],
    username: [{ required: true, message: i18n.global.t('user.usernameRulePlaceholder') }],
    name: [{ required: true, message: i18n.global.t('user.nameRulePlaceholder') }],
    password: [
        { required: true, message: i18n.global.t('user.passwordRulePlaceholder') },
        { validator: (rule, value, callback) => {
            if (form.password2 !== '') {
                dialogFormRef.value.validateField('password2');
            }
            callback();
        }}
    ],
    password2: [
        { required: true, message: i18n.global.t('user.password2RulePlaceholder') },
        { validator: (rule, value, callback) => {
            if (value !== form.password) {
                callback(new Error(i18n.global.t('user.confirmRulePlaceholder')));
            } else {
                callback();
            }
        }}
    ],
    dept_id: [{ required: true, message: i18n.global.t('user.deptRulePlaceholder') }],
    role_list: [{ required: true, message: i18n.global.t('user.roleRulePlaceholder'), trigger: 'change' }],
}));
const groups = ref([]);
const groupsProps = reactive({
    value: "id",
    multiple: true,
    checkStrictly: true,
});
const depts = ref([]);
const deptsProps = reactive({
    value: "id",
    label: "name",
    checkStrictly: true,
});
// 组件挂载时加载数据
onMounted(() => {
    getGroup();
    getDept();
});
// 自定义显示的方法
const open = (newMode = 'add') => {
    mode.value = newMode;
    visible.value = true;
};
// 自定义加载树形角色数据的方法
const getGroup = async() => {
    var res = await api.setting.role.list.get();
    groups.value = res.data.rows;
};
// 自定义加载树形部门数据的方法
const getDept = async () => {
    const res = await api.setting.dept.list.get();
    depts.value = res.data;
};
// 自定义提交表单的方法
const submit = () => {
    dialogFormRef.value.validate(async (valid) => {
        if (valid) {
            isSaveing.value = true;
            form.dept_id = deptRef.value.getCheckedNodes()[0].data.id;
            var res = null;
            try {
                if (mode.value == 'add') {
                    res = await api.setting.user.add.post(form);
                } else {
                    res = await api.setting.user.edit.post(form);
                }
                if (res.code == 200) {
                    emit('success', form, mode.value);
                    visible.value = false;
                    ElMessage.success(res.message);
                } else {
                    ElMessage.error(res.message);
                }
            } catch (error) {
                console.error('Error in setting/user/save/submit action:', error);
            } finally {
                isSaveing.value = false;
            }
        }
    });
};
// 自定义表单注入数据的方法
const setData = (data) => {
    form.id = data.id;
    form.username = data.username;
    form.avatar = data.avatar;
    form.name = data.name;
    form.email = data.email;
    form.phone = data.phone;
    form.position = data.position;
    form.role_list = data.role_list;
    form.status = data.status;
    form.dept_id = data.dept_id;
};
defineExpose({open, setData});
</script>